package com.dongbao.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;


public class ZipUtils {

    public static String readerZipFile(String packPath,String entryPath) {
        ZipFile zipFile = null;
        InputStream in = null;
        try {
            zipFile = new ZipFile(packPath);
            for (Enumeration<? extends ZipEntry> e = zipFile.getEntries(); e.hasMoreElements(); ) {
                ZipEntry entry = e.nextElement();
                if (entry.getName().equals("secretKey.key")) {
                    //读取文件的内容
                    in = zipFile.getInputStream(entry);
                    //初始值，起标志位作用
                    int len = -1;
                    //缓冲区
                    byte buf[] = new byte[128];
                    //捕获内存缓冲区的数据转换为字节数组
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    //循环读取内容,将输入流的内容放进缓冲区中
                    while ((len = in.read(buf)) != -1) {
                        //将缓冲区内容写进输出流，0是从起始偏移量，len是指定的字符个数
                        baos.write(buf, 0, len);
                    }
                    in.close();
                    baos.close();
                    String keyContent = new String(baos.toByteArray());
                    JSONObject packInfo = JSONUtil.parseObj(keyContent);
                    return JSONUtil.toJsonStr(packInfo);
                }
            }
            zipFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
